package com.bojiu.lawsearch.lawsearch.service.impl;

import com.bojiu.lawsearch.lawsearch.mapper.LabelMapper;
import com.bojiu.lawsearch.lawsearch.model.Label;
import com.bojiu.lawsearch.lawsearch.model.Page;
import com.bojiu.lawsearch.lawsearch.service.LabelService;
import com.bojiu.lawsearch.lawsearch.util.JsonResult;
import com.bojiu.lawsearch.lawsearch.util.ResultCode;
import com.bojiu.lawsearch.lawsearch.util.UtilTools;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author: afdiao
 * @Date：2020/3/8 17:24
 * @Description:
 */
@Service
@Slf4j
public class LabelServiceImpl implements LabelService {

    @Autowired
    LabelMapper labelMapper;

    @Override
    public Page<Label> getBackLabelList(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize, true);
        List list = labelMapper.selectAll();
        PageInfo pageInfo = new PageInfo(list);
        Page page = new Page(pageInfo.getPageNum(), pageInfo.getPageSize(), pageInfo.getPages(), pageInfo.getTotal(), list);
        return page;
    }

    @Override
    public JsonResult backInsert(Label label) {
        //校验标签名是否存在
        if (labelMapper.selectCountByExample(UtilTools.createExampleByKey("name", label.getName(), Label.class)) > 0) {
            log.error("标签名已存在");
            return new JsonResult(ResultCode.SAME_DATA);
        }
            labelMapper.insertSelective(label);
        return new JsonResult(ResultCode.SUCCESS);
    }

    @Override
    public JsonResult backUpdate(Label label, int id) {
        label.setId(null);
        if (labelMapper.selectCountByExample(UtilTools.createExampleByKey("name", label.getName(), Label.class)) > 0) {
            log.error("标签名已存在");
            return new JsonResult(ResultCode.SAME_DATA);
        }
        labelMapper.updateByExampleSelective(label, UtilTools.createExampleByKey("id", id, Label.class));
        return new JsonResult(ResultCode.SUCCESS);
    }

    @Override
    public void backDelete(int id) {
        labelMapper.deleteByExample(UtilTools.createExampleByKey("id", id, Label.class));
    }
}
